<template>
  <div class="cmt-container">
    <h3>发表评论</h3>
    <hr>
    <textarea placeholder="请输入要评论的内容（最多120字）" maxlength="120" v-model="msg"></textarea>

    <mt-button size="large" type="primary" @click="postComment()">发表评论</mt-button>

    <div class="cmt-list">


      <div class="cmt-item">

        <div class="cmt-item" v-for="(item,i) in article" :key="i">
          <div class="cmt-title">
            第{{ i+1 }}楼&nbsp;&nbsp;用户：{{ item.user_name }}&nbsp;&nbsp;发表时间：{{ item.add_time | dataFormat }}
          </div>
          <div class="cmt-body">
            {{ item.content == "" ? "这个用户很懒，什么都没说" : item.content}}
          </div>
        </div>

      </div>


    </div>
    <mt-button size="large" type="danger" plain @click="addlist()">加载更多</mt-button>

  </div>
</template>

<script>
  import {
    Toast
  } from "mint-ui"

  export default {
    data() {
      return {
        id: this.$route.params.id,
        pageindex: 1,
        article: [],
        msg: "",
      }
    },
    created() {
      this.getComments()
    },
    methods: {
      getComments() {
        this.$http.get('api/getcomments/' + this.id + '?pageindex=' + this.pageindex).then(result => {
          if (result.body.status === 0) {
            this.article = this.article.concat(result.body.message)
          } else {
            Toast('加载评论失败')
          }
        })
      },
      addlist() {
        this.pageindex++
        this.getComments()
      },
      postComment() {

        // 验证是否为空
        if (this.msg.trim().length === 0) {
          return Toast("评论内容不能为空")
        }
        // 发表评论
        // 参数1：请求的url地址
        // 参数2：提交服务器的数据对象
        // 参数3：定义提交的时候，表单中的数据格式
        this.$http.post("api/postcomment/" + this.id, {
          content: this.msg.trim()
        }).then(function (result) {
          if (result.body.status === 0) {
            var cmt = {
              user_name: "匿名用户",
              add_time: Date.now(),
              content: this.msg.trim()
            }
            this.article.unshift(cmt);
            this.msg = "";
            Toast('发表成功')
          }else{
            Toast('提交失败')
          }
        })

      }

    }
  }
</script>


<style lang="scss" scped>
  .cmt-container {
    .cmt-list {
      margin: 5px 0
    }

    h3 {
      font-size: 18px;
    }

    textarea {
      height: 85px;
      font-size: 14px;
      margin: 0;
    }

    .cmt-title {
      font-size: 14px;
      line-height: 30px;
      background-color: #ccc;
    }

    .cmt-body {
      text-indent: 1em;
      font-size: 12px
    }
  }
</style>